﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ETL.Business.Handlers.ProjectTimeHandler;
using ETL.Business.Handlers.SessionHandler;
using ETL.Business.Models;
using ETL.Common;

namespace ETL.Business.Helpers
{
    /// <summary>
    /// class Calc
    /// calculate time spent on projects of this week
    /// </summary>
    public class Calc
    {
        public Calc()
        {}
        public virtual void Execute(string userId, string userName)
        {
            int prjId = 0;

            Single hours = 0f;
            Single projectHours = 0f;
            Single totalHours = 0f;

            DateTime dt = DateTime.Now;
            while (dt.DayOfWeek.ToString() != "Monday")
            {
                dt = dt.AddDays(-1);
            }
            var allPrjTimes = (new GetAllProjectTimes()).Execute(userId, dt);
            if(allPrjTimes != null)
            {
                foreach (ProjectTimeModel prjTimeModel in allPrjTimes)
                {
                    if(prjTimeModel.TimeHours == null)
                    {
                        //calc time from current time
                        DateTime startTime = Convert.ToDateTime(prjTimeModel.TimeStart);
                        DateTime endTime = DateTime.Now;
                        TimeSpan ts = endTime - startTime;
                        hours = (float)ts.TotalHours;
                    }
                    else
                    {
                        hours += Convert.ToSingle(prjTimeModel.TimeHours);
                    }
                    // add total hours
                    totalHours += hours;

                    prjId = Convert.ToInt32(prjTimeModel.ProjectId);
                    if(prjId > 0)
                    {
                        projectHours += hours;
                    }
                }
            }

            // check totalHours and hours
            if (totalHours == 0)
                hours = 0;
            else
                hours = projectHours * 100 / totalHours;//percentage of project hours

            // Check managment for time spent status label
            string management = (new GetSessionData()).Execute(Constants.SessionVars.Management);
            string timespentstatus = string.Empty;
            if(management.Equals("True"))
            {
                timespentstatus = String.Format("{0:0.00}", hours) + "% of time spent on projects for " + userName + ".";
            }
            else
            {
                timespentstatus = String.Format("{0:0.00}", hours) + "% of time spent on projects"; ;
            }
            // save to session
            (new SetSessionData()).Execute(Constants.SessionVars.TimeSpentStatus, timespentstatus);

        }
    }
}
